package com.example.shgt;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.loader.content.CursorLoader;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import android.Manifest;


public class PublishActivity extends AppCompatActivity {

    // 声明控件和变量
    private EditText editTextContent; // 商品描述输入框
    private EditText editTextAddress; // 商品地址输入框
    private EditText editTextPrice; // 商品价格输入框
    private TextView textViewCancel; // 取消按钮
    private TextView textViewPublish; // 发布按钮
    private TextView textViewAddImage; // 添加图片按钮
    private TextView textViewSelectCategory; // 选择商品类别按钮
    private Spinner spinnerCategory; // 商品类别下拉菜单
    private static final int REQUEST_CODE = 100; // 自定义请求码，用于请求权限

    // 商品类别数组
    private String[] categories = {
            "手机", "奢品", "潮品", "美妆", "数码",
            "潮玩", "游戏", "图书", "美食", "文玩",
            "母婴", "家居", "乐器", "其他"
    };

    // 请求选择图片的请求码
    private static final int PICK_IMAGE_REQUEST = 1;
    private String imageCode = "0"; // 上传成功后获取的图片码
    private String userId; // 用户ID变量

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish_item); // 设置布局文件

        // 检查并请求读取外部存储权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_CODE);
        }

        // 从SharedPreferences中获取用户ID
        SharedPreferences sharedPreferences = getSharedPreferences("UserPrefs", MODE_PRIVATE);
        userId = sharedPreferences.getString("userId", "默认值"); // 获取不到时使用默认值

        // 绑定控件
        textViewCancel = findViewById(R.id.relativeLayout).findViewById(R.id.textViewCancel);
        textViewPublish = findViewById(R.id.relativeLayout).findViewById(R.id.textViewPublishFinal);
        editTextContent = findViewById(R.id.linearLayout).findViewById(R.id.editTextContent);
        editTextAddress = findViewById(R.id.editTextAddress); // 获取输入地址控件
        editTextPrice = findViewById(R.id.editTextPrice); // 获取输入价格控件
        textViewAddImage = findViewById(R.id.linearLayout2).findViewById(R.id.textViewAddImage);
        spinnerCategory = findViewById(R.id.spinnerCategory); // 获取类别下拉菜单
        textViewSelectCategory = findViewById(R.id.textViewSelectCategory); // 获取类别选择按钮

        // 设置Spinner的适配器，用于显示商品类别
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
                android.R.layout.simple_spinner_item, categories);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerCategory.setAdapter(adapter);

        // 选择类别时的点击事件：显示或隐藏Spinner
        textViewSelectCategory.setOnClickListener(v -> {
            spinnerCategory.setVisibility(spinnerCategory.getVisibility() == View.GONE ? View.VISIBLE : View.GONE);
        });

        // 选择某个类别后的操作
        spinnerCategory.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                textViewSelectCategory.setText(categories[position]); // 显示选中的类别
                spinnerCategory.setVisibility(View.GONE); // 隐藏Spinner
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });

        // 取消按钮点击事件：关闭当前页面
        textViewCancel.setOnClickListener(v -> finish());

        // 发布按钮点击事件：检查输入是否完整，提交数据
        textViewPublish.setOnClickListener(v -> {
            String content = editTextContent.getText().toString().trim(); // 获取商品描述
            String address = editTextAddress.getText().toString().trim(); // 获取地址
            String price = editTextPrice.getText().toString().trim(); // 获取价格

            // 检查输入是否为空
            if (content.isEmpty() || address.isEmpty() || price.isEmpty()) {
                Toast.makeText(PublishActivity.this, "请填写内容、地址和价格", Toast.LENGTH_SHORT).show();
            } else {
                submitProduct(content, address, price); // 提交商品信息
            }
        });

        // 添加图片按钮点击事件：打开相册选择图片
        textViewAddImage.setOnClickListener(v -> {
            Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(intent, PICK_IMAGE_REQUEST); // 打开图库选择图片
        });
    }

    // 提交商品信息
    private void submitProduct(String content, String address, String price) {
        OkHttpClient client = new OkHttpClient();

        // 获取类别ID和名称
        String typeId = String.valueOf(spinnerCategory.getSelectedItemPosition() + 1); // 商品类别ID
        String typeName = spinnerCategory.getSelectedItem().toString(); // 商品类别名称

        // 构建JSON请求体
        String json = String.format("{\"addr\":\"%s\",\"content\":\"%s\",\"imageCode\":\"%s\",\"price\":\"%s\",\"typeId\":\"%s\",\"typeName\":\"%s\",\"userId\":\"%s\"}",
                address, content, imageCode, price, typeId, typeName, userId);

        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);

        // 构建HTTP请求
        Request request = new Request.Builder()
                .url("https://api-store.openguet.cn/api/member/tran/goods/add") // 商品发布API地址
                .post(body)
                .addHeader("appId", "479dbe79299a4653ada0432942111871") // API请求头中的appId
                .addHeader("appSecret", "14687c6d2cc860b264339b1d93bf409f2bb6c") // API请求头中的appSecret
                .build();

        // 发送请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                // 请求失败，提示用户
                runOnUiThread(() -> Toast.makeText(PublishActivity.this, "发布失败", Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // 请求成功
                if (response.isSuccessful()) {
                    runOnUiThread(() -> {
                        Toast.makeText(PublishActivity.this, "发布成功", Toast.LENGTH_SHORT).show();
                        finish(); // 发布成功后关闭页面
                    });
                } else {
                    runOnUiThread(() -> Toast.makeText(PublishActivity.this, "发布失败", Toast.LENGTH_SHORT).show());
                }
            }
        });
    }

    // 接受图片选择结果并上传
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null) {
            Uri imageUri = data.getData(); // 获取图片的URI
            uploadImage(imageUri); // 上传图片
        }
    }

    // 上传图片到服务器
    private void uploadImage(Uri imageUri) {
        OkHttpClient client = new OkHttpClient();

        String filePath = getRealPathFromURI(imageUri); // 获取图片的真实路径
        if (filePath == null) {
            Toast.makeText(this, "无法获取图片路径", Toast.LENGTH_SHORT).show();
            return;
        }

        // 构建多部分表单请求体
        RequestBody fileBody = RequestBody.create(MediaType.parse("image/jpeg"), new File(filePath));

        MultipartBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("fileList", "image.jpeg", fileBody) // 添加图片数据
                .build();

        // 构建HTTP请求
        Request request = new Request.Builder()
                .url("https://api-store.openguet.cn/api/member/tran/image/upload") // 图片上传API地址
                .post(requestBody)
                .addHeader("appId", "479dbe79299a4653ada0432942111871")
                .addHeader("appSecret", "14687c6d2cc860b264339b1d93bf409f2bb6c")
                .build();

        // 发送请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                Log.e("UploadError", "Error: " + e.getMessage()); // 打印错误日志
                runOnUiThread(() -> Toast.makeText(PublishActivity.this, "图片上传失败", Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d("UploadResponse", "Response Code: " + response.code()); // 打印响应码
                if (response.isSuccessful()) {
                    String responseData = response.body().string(); // 获取响应数据
                    try {
                        // 解析JSON响应，获取imageCode
                        JSONObject jsonResponse = new JSONObject(responseData);
                        JSONObject data = jsonResponse.getJSONObject("data");
                        imageCode = data.getString("imageCode"); // 存储获取的图片码
                        // 如果需要解析图片URL列表，可以在此处进行

                        runOnUiThread(() -> {
                            Toast.makeText(PublishActivity.this, "图片上传成功，code: " + imageCode, Toast.LENGTH_SHORT).show(); // 提示用户上传成功
                            // 此处可进行其他UI更新
                        });
                    } catch (Exception e) {
                        e.printStackTrace(); // 打印异常信息
                        runOnUiThread(() -> Toast.makeText(PublishActivity.this, "解析响应失败", Toast.LENGTH_SHORT).show()); // 提示解析失败
                    }
                } else {
                    runOnUiThread(() -> Toast.makeText(PublishActivity.this, "图片上传失败", Toast.LENGTH_SHORT).show()); // 提示上传失败
                }
            }
        });
    }

    // 处理权限请求结果
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限被授予，可以进行图片选择
                Toast.makeText(this, "权限已授予", Toast.LENGTH_SHORT).show();
            } else {
                // 权限被拒绝，提示用户
                Toast.makeText(this, "权限被拒绝，无法选择图片", Toast.LENGTH_SHORT).show();
            }
        }
    }
    // 根据URI获取真实文件路径
    private String getRealPathFromURI(Uri contentUri) {
        String[] proj = { MediaStore.Images.Media.DATA }; // 要查询的列
        CursorLoader loader = new CursorLoader(getApplicationContext(), contentUri, proj, null, null, null); // 创建CursorLoader
        Cursor cursor = loader.loadInBackground(); // 异步加载数据
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); // 获取列索引
        cursor.moveToFirst(); // 移动到第一行
        return cursor.getString(column_index); // 返回文件路径
    }

}
